//
//  HBPanButton.m
//  WhiteSpots白点
//
//  Created by Mike on 16/6/20.
//  Copyright © 2016年 shikee_Chan. All rights reserved.
//


#define IOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 ? YES : NO)
#define StatusBarHeight (IOS7==YES ? 0 : 20)
#define BackHeight      (IOS7==YES ? 0 : 15)

#define fNavBarHeigth (IOS7==YES ? 64 : 44)

#define fDeviceWidth ([UIScreen mainScreen].bounds.size.width)
#define fDeviceHeight ([UIScreen mainScreen].bounds.size.height-StatusBarHeight)

#import "HBPanButton.h"

@interface HBPanButton ()
@property (nonatomic, assign) float btnWidth;
@property (nonatomic, assign) float btnheight;
@end

@implementation HBPanButton

- (void)setEnablePan:(BOOL)enablePan{
    _enablePan = enablePan;
    _btnWidth  = self.frame.size.width/2;
    _btnheight = self.frame.size.height/2;
    if (_enablePan) {
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
        [self addGestureRecognizer:panRecognizer];
        
        panRecognizer.maximumNumberOfTouches = 1;
        panRecognizer.delegate = self;
    }
}

-(void)handlePanFrom:(UIPanGestureRecognizer*)recognizer
{
    //处理拖动操作,拖动是基于imageview，如果经过旋转，拖动方向也是相对imageview上下左右移动，而不是屏幕对上下左右
    CGPoint translation = [recognizer translationInView:recognizer.view];
    
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
//    NSLog(@"%f %f",recognizer.view.center.y+translation.y,fDeviceHeight-49);
    [recognizer setTranslation:CGPointZero inView:recognizer.view];
    
    if(recognizer.state == UIGestureRecognizerStateEnded){
        if (recognizer.view.center.x + translation.x<fDeviceWidth/2) {
            [UIView animateWithDuration:0.3f animations:^{
                recognizer.view.center = CGPointMake(recognizer.view.frame.size.width/2, recognizer.view.center.y + translation.y);
            }];
        }else{
            [UIView animateWithDuration:0.3f animations:^{
                recognizer.view.center = CGPointMake(fDeviceWidth-recognizer.view.frame.size.width/2, recognizer.view.center.y + translation.y);
            }];
        }
        if (recognizer.view.center.y <_btnheight+20) {
            [UIView animateWithDuration:0.3f animations:^{
                recognizer.view.center = CGPointMake(recognizer.view.center.x, _btnheight+20);
            }];
        }
        else if (recognizer.view.center.y >fDeviceHeight-_btnheight-50){
            [UIView animateWithDuration:0.3f animations:^{
                recognizer.view.center = CGPointMake(recognizer.view.center.x, fDeviceHeight-_btnheight-50);
            }];
        }
    }
}

@end
